﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Songhay.Net
{
    using Models;
    using Xml;

    /// <summary>
    /// Static helpers for <see cref="RemoteResource"/>.
    /// </summary>
    public static class RemoteResourceUtility
    {
        /// <summary>
        /// Lists the IIS directory.
        /// </summary>
        /// <param name="directoryUri">The directory URI.</param>
        /// <returns>Returns a list of <see cref="RemoteResource"/>.</returns>
        public static List<RemoteResource> ListIISDirectory(Uri directoryUri)
        {
            return ListIISDirectory(directoryUri, null);
        }

        /// <summary>
        /// Lists the IIS directory.
        /// </summary>
        /// <param name="directoryUri">The directory URI.</param>
        /// <param name="baseUriOfOutput">The base URI of output.</param>
        /// <returns>Returns a list of <see cref="RemoteResource"/>.</returns>
        public static List<RemoteResource> ListIISDirectory(Uri directoryUri, Uri baseUriOfOutput)
        {
            if(baseUriOfOutput == null)
            {
                baseUriOfOutput = new Uri(string.Format("{0}://{1}:{2}",
                    directoryUri.Scheme, directoryUri.Host, directoryUri.Port));
            }

            var s = HttpVerbUtility.Get(directoryUri);
            s = HtmlUtility.ConvertToXml(s);
            s = s.Replace("<A", "<a");
            s = s.Replace("</A>", "</a>");
            s = s.Replace("HREF=", "href=");

            if(string.IsNullOrEmpty(s)) return null;

            var x = XDocument.Parse(s);
            var list = new List<RemoteResource>();

            if(x.Descendants("a").Count() == 0) return null;
            if(x.Descendants("a").Attributes("href").Count() == 0) return null;

            x.Descendants("a").Where(a => a.Value.Contains(".xaml")).ToList().ForEach(d =>
            {
                s = d.Attribute("href").Value;
                if(s.StartsWith("/")) s = s.Remove(0, 1);
                s = string.Concat(baseUriOfOutput.AbsoluteUri, s);
                var location = new Uri(s, UriKind.Absolute);
                var displayName = location.Segments.Last();
                displayName = displayName.Replace(".xaml", string.Empty);
                displayName = displayName.Replace("%20", " ");
                var resource = new RemoteResource { DisplayName = displayName, Location = location };
                list.Add(resource);
            });

            return list;
        }
    }
}
